from __future__ import absolute_import
import logging
from os.path import join

logger = logging.getLogger('commands.pkgr.RunTxn')

from forest.api import Command, get_tool


class Run(Command):
    __register__ = 'commands.pkgr.Run'


    def run(self, config):
        pkgr = config.get('_pkgr')
        trans = config.get('_txn')
        installtree = config.get_install_root()
        #print trans.newpackages()

        logger.info("Runnng pkgr transaction...")

        try:
            problems = pkgr.run_transaction(trans)
        except Exception as e:
            if installtree != '/':
                self.unmount_chroot(installtree)
            print e
            raise

        if problems:
            if installtree != '/':
                self.unmount_chroot(installtree)
            print problems
            raise Exception(problems)
            
        if installtree != '/':
            self.unmount_chroot(installtree)
        get_tool('system.remove')(join(installtree, 'var', 'lib', 'pkgr'))



    def unmount_chroot(self, installtree):
        get_tool('system.unmount')(join(installtree, 'dev'), lazy=True)
        get_tool('system.unmount')(join(installtree, 'proc'), lazy=True)
        get_tool('system.unmount')(join(installtree, 'sys'), lazy=True)
